/// 本文件由reazhuang@outlook.com开发编写
/// 20211210重构完成
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Text;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core.Extensions;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:treecontainer", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.NormalOrSelfClosing)]
	public class TreeContainerTagHelper : BaseElementTag
	{
		#region 公开属性

		public ModelExpression Vm { get; set; }
		/// <summary>
		/// 默认加载的页面
		/// </summary>
		public string AutoLoadUrl { get; set; }

		/// <summary>
		/// 当嵌套Grid时使用，树会把点击节点的ID传递给绑定的IdField，比如Searcher.xxxId
		/// </summary>
		public ModelExpression IdField { get; set; }

		/// <summary>
		/// 自动加载首节点
		/// 默认为false
		/// </summary>
		[HtmlAttributeName("is-autoload")]
		public bool IsAutoLoad { get; set; }

		public string ItemUrl { get; set; }

		/// <summary>
		/// 当嵌套Grid时使用，树会把点击节点的层级（从0开始的整形）传递给绑定的LevelField，比如Searcher.level
		/// </summary>
		public ModelExpression LevelField { get; set; }

		public bool ShowLine { get; set; }

		public string Title { get; set; }

		public int TreeWidth { get; set; } = 150;

		#endregion

		#region 公开事件

		/// <summary>
		/// 加载页面之后执行的事件
		/// 函数名称，可传闭包
		/// </summary>
		public string AfterLoadEvent { get; set; }

		/// <summary>
		/// 加载页面之前执行
		/// 函数名称，可传闭包
		/// 参数为data
		/// obj.data 得到当前点击的节点数据
		/// obj.state 得到当前节点的展开状态：open、close、normal
		/// obj.elem 得到当前节点元素
		/// </summary>
		public string ClickFunc { get; set; }

		#endregion

		#region 待删除

		[Obsolete("使用item-url替代")]
		public ModelExpression Items { get; set; }

		#endregion

		//public TreeContainerTagHelper()
		//{
		//	CascadeAction = para => para?.Invoke(this);
		//}
		//Action<Action<TreeContainerTagHelper>> CascadeAction;
		protected const string REQUIRED_ATTR_NAME = "item-url";

		public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
		{
			SetCascadeValue(context, this);

			output.TagName = "div";
			output.TagMode = TagMode.StartTagAndEndTag;
			Id = string.IsNullOrEmpty(Id) ? Guid.NewGuid().ToNoSplitString() : Id;
			output.Attributes.Add("id", "top" + Id);
			output.Attributes.Add("class", "layui-row wtm-treecontainer donotuse_fill");

			var inside = await output.GetChildContentAsync();

			StringBuilder builder = new StringBuilder();
			builder.Append($@"
<div id='wtTree_{Id}' class='wtm-treecontainer-tree' style='width:{TreeWidth}px;'>
</div>

<div id='wtContainer_{Id}' class='wtm-treecontainer-container donotuse_pdiv'>
	{inside.GetContent()}
</div>
");

			builder.Append($@"
<script>
wtm.treecontainer_Render({{
id:'{Id}',
onlyIconControl:true,
showCheckbox:false,
showLine:{GetBooleanString(ShowLine)},
customClick:'{ClickFunc}',
gridId:'{GetDictValue("grid-id")}',
searchPanelId:'{GetDictValue("search-panel-id")}',
levelField:'{LevelField?.Name?.Remove(0,9)}',
idField:'{IdField?.Name?.Remove(0, 9)}',
url:'{ItemUrl}',
autoLoad:{GetBooleanString(IsAutoLoad)},
autoLoadUrl:'{AutoLoadUrl}',
afterLoadEvent:'{AfterLoadEvent}',
}});
</script>
");
			output.Content.SetHtmlContent(builder.ToString());

			base.Process(context, output);
		}

		//protected override void SetCascade(TagHelperContext context)
		//{
		//	context.SetItem(nameof(TreeContainerTagHelper), CascadeAction);
		//	context.SetItem("treecontainer-autoload", IsAutoLoad);
		//}
	}
}